package per.turtle.system.controller;

import cn.hutool.core.util.StrUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import per.turtle.common.core.web.controller.BaseController;
import per.turtle.common.core.web.entity.CommonResult;
import per.turtle.common.core.web.page.TableDataInfo;
import per.turtle.common.log.annotation.Log;
import per.turtle.common.log.enums.BusinessType;
import per.turtle.common.security.annotation.OnlyInterService;
import per.turtle.common.security.annotation.PreAuthorize;
import per.turtle.system.entity.SysDept;
import per.turtle.system.service.ISysDeptService;
import per.turtle.system.vo.TreeSelect;

import java.util.List;

/**
 * @author turtle
 */
@AllArgsConstructor
@Api(value = "dept", tags = {"dept_部门管理模块"})
@RequestMapping("dept")
@RestController
public class SysDeptController extends BaseController {

    private final ISysDeptService deptService;

    @ApiOperation(value = "新增部门", notes = "新增部门")
    @Log(title = "部门管理", businessType = BusinessType.INSERT)
    @PostMapping("add")
    @PreAuthorize(hasPermission = "system:dept:add")
    public CommonResult<Void> add(@Validated @RequestBody SysDept dept) {
        if (!deptService.checkDeptNameUnique(dept)) {
            return CommonResult.error("新增部门【" + dept.getDeptName() + "】失败，部门名称已存在");
        }
        return result(deptService.insertDept(dept));
    }

    @ApiOperation(value = "修改部门", notes = "修改部门")
    @Log(title = "部门管理", businessType = BusinessType.UPDATE)
    @PreAuthorize(hasPermission = "system:dept:edit")
    @PutMapping("edit")
    public CommonResult<Void> edit(@Validated @RequestBody SysDept dept) {
        if (!deptService.checkDeptNameUnique(dept)) {
            return CommonResult.error("修改部门【" + dept.getDeptName() + "】失败，部门名称已存在");
        } else if (dept.getParentId().equals(dept.getDeptId())) {
            return CommonResult.error("修改部门【" + dept.getDeptName() + "】失败，上级部门不能是自己");
        } else if (dept.getIsDisabled() && deptService.hasNormalChildrenDeptById(dept.getDeptId()) > 0) {
            return CommonResult.error("该部门包含未停用的子部门！");
        }
        return result(deptService.updateDept(dept));
    }

    @ApiOperation(value = "查询部门列表", notes = "查询部门列表（排除节点）")
    @GetMapping("list/exclude/{deptId}")
    @PreAuthorize(hasPermission = "system:dept:list")
    public CommonResult<List<SysDept>> excludeChild(@PathVariable(value = "deptId", required = false) String deptId) {
        List<SysDept> depts = deptService.selectDeptList(new SysDept());
        depts.removeIf(d -> d.getDeptId().equals(deptId) || StrUtil.split(d.getAncestors(), StrUtil.C_COMMA).contains(deptId));
        return CommonResult.success(depts);
    }

    @GetMapping("getDeptIdsByRole/{roleId}")
    @OnlyInterService
    public CommonResult<List<String>> getDeptIdsByRole(@PathVariable(value = "roleId") String roleId) {
        return CommonResult.success(deptService.selectDeptIdsByRole(roleId));
    }

    @GetMapping("getDeptIdsWithChildByUser/{deptId}")
    @OnlyInterService
    public CommonResult<List<String>> getDeptIdsWithChildByUser(@PathVariable(value = "deptId") String deptId) {
        return CommonResult.success(deptService.getDeptIdsWithChildByDeptId(deptId));
    }

    @ApiOperation(value = "根据部门编号获取详细信息", notes = "根据部门编号获取详细信息")
    @GetMapping("{deptId}")
    @PreAuthorize(hasPermission = "system:dept:query")
    public CommonResult<SysDept> getInfo(@PathVariable String deptId) {
        return CommonResult.success(deptService.selectDeptById(deptId));
    }

    @ApiOperation(value = "获取部门列表或分页", notes = "获取部门列表或分页（区别于是否传入分页参数）")
    @PostMapping("list")
    @PreAuthorize(hasPermission = "system:dept:list")
    public TableDataInfo<SysDept> list(@RequestBody SysDept dept) {
        List<SysDept> depts = startPage(s -> deptService.selectDeptList(dept));
        return getDataTable(depts);
    }

    @ApiOperation(value = "删除部门", notes = "删除部门")
    @DeleteMapping("{deptId}")
    @Log(title = "部门管理", businessType = BusinessType.DELETE)
    @PreAuthorize(hasPermission = "system:dept:remove")
    public CommonResult<Void> remove(@PathVariable String deptId) {
        if (deptService.hasChildByDeptId(deptId)) {
            return CommonResult.error("存在下级部门,不允许删除");
        }
        if (deptService.checkDeptExistUser(deptId)) {
            return CommonResult.error("部门存在用户,不允许删除");
        }
        return result(deptService.deleteDeptById(deptId));
    }

    @ApiOperation(value = "获取部门下拉树列表", notes = "获取部门下拉树列表")
    @PostMapping("treeSelect")
    @PreAuthorize(hasPermission = "system:dept:list")
    public CommonResult<List<TreeSelect>> treeSelect(@RequestBody SysDept dept) {
        List<SysDept> depts = deptService.selectDeptList(dept);
        return CommonResult.success(deptService.buildDeptTreeSelect(depts));
    }

}
